<?php

namespace App\Http\Controllers;

/**
 * Provide response generating functions
 * typically used in various situtaions
 */
trait Responser {

    /**
     * Render a HTML response
     * @param  String $view View path
     * @param  Array $data Data to be passsed to view
     * @return HTTPResponse
     */
    static function resView($tpl, $dat)
    {
        return view($tpl)->with($dat);
    }

    /**
     * Send a JSON response for API
     * @param  Array $data Data array
     * @return HTTPResponse
     */
    static function resOutputJson($data, $code=200)
    {
        return response()->json($data, $code);
        //return response()->json($data, $code)->header('Content-Type', 'application/javascript');
    }

    /**
     * Send a file download response
     * @param  String  $path          File path
     * @param  boolean $forceDownload Force browser to initiate a download
     * @param  boolean $deleteFile    Whether the file should be deleted after download
     * @return HTTPResponse
     */
    static function resDownload($path, $forceDownload = true, $deleteFile = false)
    {
        if ($forceDownload) {
            return response()->download($path)->deleteFileAfterSend($deleteFile);
        }

        return response()->file($path);
    }

    /**
     * Response with a customized status json
     * @param  Enum $status  success or error
     * @param  String $message Response message
     * @param  Mixed $data    Data to be passed along
     * @return HTTPResponse
     */
    static function resOutput( $res, $msg='', $dat=null)
    {
        return self::resOutputJson([
            'res' => $res,
            'msg' => $msg,
            'dat' => $dat
        ]);
    }


    static function resSuccess($msg='', $dat=null)
    {
        return self::resOutput(1, $msg, $dat);
    }


    static function resFail($msg='', $dat=null)
    {
        return self::resOutput(0, $msg, $dat);
    }


    static function resLogin ($msg='', $dat=null)
    {
        return self::resOutput(-1, $msg, $dat);
    }


    /**
     * 数据不存在
     * @param $name string 名称。
     * @param $dat mixed 返回数据，默认null。
     * */
    static function resFailOfNoData ($name, $dat=null) {
        return static::resFail($name.'不存在。', $dat);
    }


    /**
     * 文件未上传
     * @param $name string 名称。
     * @param $dat mixed 返回数据，默认null。
     * */
    static function resFailOfNoUpload ($name, $dat=null) {
        return static::resFail($name.'文件未上传。', $dat);
    }


}